//
//  TcpConnector.m
//  socketDemo
//
//  Created by 吳瀾洲 on 2020/8/7.
//  Copyright © 2020 kingboyrang. All rights reserved.
//

#import "TcpConnector.h"

@implementation TcpConnector


/**
 * @brief 发送数据报文
 * @param aDataPack 数据报文
 */
- (BOOL)sendDataPack:(BaseDataPack*)aDataPack{
    
    if (self.socket && [self.socket isConnected]) {
        
        [self.socket writeData:aDataPack.bodyData withTimeout:-1 tag:aDataPack.packetId];
        
    }
    return NO;
}

#pragma mark GCDAsyncSocketDelegate Methods

- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket{
    NSLog(@"didAcceptNewSocket  =%@",newSocket);
}

// 已经连接到服务器
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(nonnull NSString *)host port:(uint16_t)port{
    NSLog(@"连接成功 : %@---%d",host,port);
    //连接成功或者收到消息，必须开始read，否则将无法收到消息,
    //不read的话，缓存区将会被关闭
    // -1 表示无限时长 ,永久不失效
    //[self.socket readDataWithTimeout:-1 tag:10086];
    if (self.connectStateChangedBlock) {
        self.connectStateChangedBlock(TcpConnectSuccess);
    }
    if (self.delegate&&[self.delegate respondsToSelector:@selector(didConnectHostState:)]) {
        [self.delegate didConnectHostState:TcpConnectSuccess];
    }
}

// 连接断开
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
    NSLog(@"断开 socket连接 原因:%@",err);
    if (err) {
        if (self.connectStateChangedBlock) {
            self.connectStateChangedBlock(TcpConnectFailed);
        }
        if (self.delegate&&[self.delegate respondsToSelector:@selector(didConnectHostState:)]) {
            [self.delegate didConnectHostState:TcpConnectFailed];
        }
    }else{
        if (self.connectStateChangedBlock) {
            self.connectStateChangedBlock(TcpConnectClose);
        }
        if (self.delegate&&[self.delegate respondsToSelector:@selector(didConnectHostState:)]) {
            [self.delegate didConnectHostState:TcpConnectClose];
        }
    }
    
}

//已经接收服务器返回来的数据
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    NSLog(@"接收到tag = %ld : %ld 长度的数据",tag,data.length);
    //连接成功或者收到消息，必须开始read，否则将无法收到消息
    //不read的话，缓存区将会被关闭
    // -1 表示无限时长 ， tag
    [self.socket readDataWithTimeout:-1 tag:10086];
}

//消息发送成功 代理函数 向服务器 发送消息
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{
    NSLog(@"%ld 发送数据成功",tag);
    if (self.sendDataStateBlock) {
        self.sendDataStateBlock(YES, tag, nil);
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(didSendDataState:tag:error:)]) {
        NSError *error = nil;
        [self.delegate didSendDataState:YES tag:tag error:error];
    }
}

@end
